package action;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.heantai.easystruts.controller.Action;
import com.heantai.easystruts.form.ActionForm;
import org.apache.commons.beanutils.BeanUtils;

import dao.DaoFactory;
import dao.UserDao;
import entity.User;
import form.RegisterForm;

public class RegisterAction extends Action {

	@Override
	public String execute(ActionForm actionForm,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		RegisterForm registerForm=(RegisterForm) actionForm;
		HttpSession session = request.getSession();
		String validateCodeOfSession = (String) session
				.getAttribute("validateCode");
		String validateCode = request.getParameter("validateCode")
				.toUpperCase();
		if (!validateCodeOfSession.equals(validateCode)) {
			request.setAttribute("validateCodeErr", "验证码错误");
			return "validateCodeErr";
		}
		String userName = registerForm.getUserName();
		UserDao dao = DaoFactory.getInstance(UserDao.class);
		User u = dao.findByUserName(userName);
		if (u != null) {
			request.setAttribute("userExisted", "用户名己存在，请更换");
			return "userExisted";
		}
		u=new User();
		BeanUtils.copyProperties(u, registerForm);
		String name = request.getParameter("name");
		String passWord = request.getParameter("passWord");
		int age = Integer.parseInt(request.getParameter("age"));
		int gender = Integer.parseInt(request.getParameter("gender"));
		String phone = request.getParameter("phone");
		u = new User(userName, passWord, name, age, gender, phone);
		int id = dao.save(u);
		String path = session.getServletContext().getRealPath("photos");
		File userPhotosFolder = new File(path + "/photo_" + id);
		userPhotosFolder.mkdirs();
		return "login";
	}
//	User user2 = new User();
//	//按属性名进行匹配
//	BeanUtils.copyProperties(user2, rForm);
//	dao.save(user2);
}
